using B.S.Medical.Api.Read.Application.Command.Payment;
using B.S.Medical.Domain.Doctor;
using B.S.Medical.Domain.Medical;
using B.S.Medical.Domain.Payment;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Medical.Api.Read.Application.Handler.Payment
{
    /// <summary>
    /// 查询患者余额和充值记录处理器
    /// </summary>
    public class GetPatientBalanceHandler : IRequestHandler<GetPatientBalanceCommand, ApiResult<PatientBalanceInfoDto>>
    {
        private readonly IBaseRepository<PaymentRecordModel> _paymentRecordRepository;
        private readonly IBaseRepository<PatientModel> _patientRepository;
        private readonly IBaseRepository<PatientBalance> _patientBalanceRepository;
        private readonly ILogger<GetPatientBalanceHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public GetPatientBalanceHandler(
            IBaseRepository<PaymentRecordModel> paymentRecordRepository,
            IBaseRepository<PatientModel> patientRepository,
            IBaseRepository<PatientBalance> patientBalanceRepository,
            ILogger<GetPatientBalanceHandler> logger)
        {
            _paymentRecordRepository = paymentRecordRepository;
            _patientRepository = patientRepository;
            _patientBalanceRepository = patientBalanceRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理查询患者余额和充值记录命令
        /// </summary>
        public async Task<ApiResult<PatientBalanceInfoDto>> Handle(GetPatientBalanceCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation($"开始查询患者ID为 {request.PatientId} 的余额和充值记录");

                // 设置默认时间范围（如果未提供）
                var endDate = request.EndDate ?? DateTime.Now;
                var startDate = request.StartDate ?? endDate.AddYears(-1); // 默认查询一年内的记录

                // 查询患者信息
                var patient = _patientRepository.GetAll()
                    .Where(p => p.Id == request.PatientId && !p.IsDeleted)
                    .FirstOrDefault();

                if (patient == null)
                {
                    _logger.LogWarning($"未找到患者: {request.PatientId}");
                    return new ApiResult<PatientBalanceInfoDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到患者信息",
                    };
                }

                // 查询患者余额
                var patientBalance = _patientBalanceRepository.GetAll()
                    .Where(b => b.PatientId == request.PatientId && !b.IsDeleted)
                    .FirstOrDefault();

                decimal currentBalance = patientBalance?.Balance ?? 0;

                // 查询充值记录（ItemName为"余额充值"且已支付的记录）
                var rechargeRecords = _paymentRecordRepository.GetAll()
                    .Where(p => p.PatientId == request.PatientId 
                           && !p.IsDeleted 
                           && p.IsPaid 
                           && p.ItemName == "余额充值"
                           && p.PayTime >= startDate
                           && p.PayTime <= endDate)
                    .OrderByDescending(p => p.PayTime)
                    .ToList();

                // 获取最后一次充值时间
                var lastRechargeTime = rechargeRecords.Any() ? rechargeRecords.First().PayTime : null;

                // 构建返回结果
                var result = new PatientBalanceInfoDto
                {
                    PatientId = patient.Id,
                    PatientName = patient.Name,
                    IdCard = patient.IdCard,
                    PhoneNumber = patient.Phone,
                    CurrentBalance = currentBalance,
                    LastRechargeTime = lastRechargeTime,
                    RechargeRecords = rechargeRecords.Select(r => new RechargeRecordDto
                    {
                        Id = r.Id,
                        OrderNo = r.OrderNo,
                        Amount = r.Amount,
                        PayType = r.PayType ?? "未知",
                        PayTime = r.PayTime,
                        CreatedTime = r.CreatedTime,
                        PayStatus = r.PayStatus ?? "已支付"
                    }).ToList()
                };

                _logger.LogInformation($"查询到患者 {patient.Name}({patient.Id}) 的余额: {currentBalance}，充值记录数量: {result.RechargeRecords.Count}");

                return new ApiResult<PatientBalanceInfoDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询患者余额和充值记录失败: PatientId={request.PatientId}, Error={ex.Message}");
                return new ApiResult<PatientBalanceInfoDto>
                {
                    Code = ApiEnum.Error,
                    Msg = $"查询患者余额和充值记录失败: {ex.Message}"
                };
            }
        }
    }
} 